package com.design02_Structural.pattern08_decorator;

import java.util.Base64;

/**
 * @ClassName EncryptionDataDecorator
 * @Description TODO
 * @Author zhangjunhao
 * @DATE 2023/9/4 23:32
 */
public class EncryptionDataDecorator extends DataLoaderDecorator {

    public EncryptionDataDecorator(DataLoader wrapper) {
        super(wrapper);
    }

    @Override
    public String read() {
        //把读取到的信息传给下面解密,然后解密结束后再返回
        String decode = decode(super.read());
        return decode;
    }

    @Override
    public void write(String data) {
        //业务的扩张
        super.write(data);
        //也可以进行业务的扩张
    }


    //加密操作
    private String encode(String data) {
        try {
            Base64.Encoder encoder = Base64.getEncoder();
            byte[] bytes = data.getBytes("UTF-8");
            String result = encoder.encodeToString(bytes);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //解密
    private String decode(String data) {
        try {
            Base64.Decoder decoder = Base64.getDecoder();
            String result = new String(decoder.decode(data),
                    "UTF-8");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
